package com.ptswitch.material.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.NoParameters;
import org.apache.struts2.interceptor.ParameterAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hxzon.project.Page;
import com.opensymphony.xwork2.ActionContext;
import com.ptswitch.material.model.Uzer;
import com.ptswitch.material.service.BomService;
import com.ptswitch.material.service.EMailAddressService;
import com.ptswitch.material.service.ExcelService;
import com.ptswitch.material.service.HLogService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.service.UploadService;
import com.ptswitch.material.service.UserService;

public class ActionSupport implements /*NoParameters,*/ParameterAware{
	protected Logger logger=LoggerFactory.getLogger(getClass());
	@Resource
	protected MaterialService materialSer;
	@Resource
	protected BomService bomSer;
//	@Resource
//	protected BomMaterialService bomMaterialSer;
	@Resource
	protected HLogService hlogSer;
	@Resource
	protected ExcelService excelSer;
	@Resource
	protected UploadService uploadSer;
	@Resource
	protected EMailAddressService eMailAddressSer;
	@Resource
	protected UserService userSer;
	//model
	protected String id;
	protected Map display=new HashMap();
	protected Page page=new Page();
	protected Map<String,String[]> parameters;

	protected boolean isPostMethod() {// POST,GET
		return "POST".equals(ServletActionContext.getRequest().getMethod());
	}

	protected boolean isGetMethod() {
		return "GET".equals(ServletActionContext.getRequest().getMethod());
	}

	protected Uzer visitor() {
		String username = getCookie("username");
		String password = getCookie("password");
		Uzer visitor = userSer.getByNameAndPassword(username, password, false);
		if (visitor == null) {
			visitor = new Uzer();
		}
		ActionContext.getContext().getSession().put("visitor", visitor);
		return visitor;
	}

	protected void login(Uzer user) {
		ActionContext.getContext().getSession().put("visitor", user);
		addCookie("username",user.getUsername());
		addCookie("password",user.getPassword());
	}

	protected void logout2() {
		ActionContext.getContext().getSession().put("visitor", new Uzer());
		addCookie("username",null);
		addCookie("password",null);
	}

//	public static String msg() {
//		ActionContext act = ActionContext.getContext();
//		String msg = (String) act.getSession().get("msg");
//		return msg;
//	}

	protected void putMsg(String msg) {
		Map session = ActionContext.getContext().getSession();
		String msg1 = (String) session.get("msg");
		if ((msg1 != null) && (msg1.endsWith("\t")))
			msg = msg1 + msg;
		session.put("msg", msg);
	}

	protected void putSession(String key, Object value) {
		ActionContext.getContext().getSession().put(key, value);
	}
	
	protected Object getSession(String key){
		return ActionContext.getContext().getSession().get(key);
	}
	
	protected void addCookie(String name,String value){
		Cookie cookie=new Cookie(name,value);
		cookie.setMaxAge(value!=null?1209600:0);
		ServletActionContext.getResponse().addCookie(cookie);
	}
	
	protected String getCookie(String name){
		Cookie[] cookies=ServletActionContext.getRequest().getCookies();
		for(Cookie cookie:cookies){
			if(cookie.getName().equals(name)){
				return cookie.getValue();
			}
		}
		return null;
	}

	protected void mustLogin() {
		if ((visitor().getUsername().equals("guest"))) {
			throw new AuthenticationException("请登录");
		}
	}

	protected void mustAdmins() {
		if (visitor().getAdminGrade() > 1) {
			throw new AuthenticationException("请登录");
		}
	}

	protected void mustAdmin() {
		if (visitor().getAdminGrade() != 0) {
			throw new AuthenticationException("请登录");
		}
	}

	protected void mustSelf(Uzer user) {
		if (!visitor().getUsername().equals(user)) {
			throw new AuthenticationException("请登录");
		}
	}

	protected void checkRandAjax(String rand) {
		ActionContext act = ActionContext.getContext();
		try {
			if (rand.equals(act.getSession().get("rand"))) {
				ServletActionContext.getResponse().getWriter().write("right");
				return;
			}
			ServletActionContext.getResponse().getWriter().write("wrong");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected boolean checkRand(String rand) {
		ActionContext act = ActionContext.getContext();
		return rand.equals(act.getSession().get("rand"));
	}

	protected void ajax(String msg) {
		try {
			ServletActionContext.getResponse().getWriter().write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	static String parentPath;

	public static String getParentPath() {
		if (parentPath == null) {
			parentPath = ServletActionContext.getServletContext().getRealPath("/");
			// last is /
			System.out.println(parentPath);
		}
		return parentPath;
	}

	static String savePath;

	public static String getSavePath() {
		if (savePath == null) {
			savePath = getParentPath() + "/WEB-INF/upload/";
		}
		return savePath;
	}

	public static String getContextPath() {
		HttpServletRequest sc = ServletActionContext.getRequest();
		return sc.getScheme() + "://" + sc.getLocalAddr() + ":" + sc.getLocalPort() + sc.getContextPath();
	}

	public static class AuthenticationException extends RuntimeException {
		private static final long serialVersionUID = -4824667849464341844L;

		public AuthenticationException(String message) {
			super(message);
		}
	}
	
	//get 
	public Map getDisplay(){
		return display;
	}
	
	public Page getPage(){
		return page;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setParameters(Map<String, String[]> parameters) {
		this.parameters = parameters;
//		for(Entry<String, String[]> entry:parameters.entrySet()){
//			String[] value=entry.getValue();
//			for(int i=0;i<value.length;i++){
//				value[i]=value[i].trim();
//			}
//		}
		for(String[] value:parameters.values()){
			for(int i=0;i<value.length;i++){
				value[i]=value[i].trim();
			}
		}
	}

	public String getStringParameter(String name) {
		String[] value = parameters.get(name);
		if (value != null) {
			return parameters.get(name)[0];
		}
		return null;
	}

	public void setPageParameter() {
		String currentPage = getStringParameter("page.currentPage");
		if (currentPage != null) {
			page.setCurrentPage(Long.valueOf(currentPage));
		}
		String pageSize = getStringParameter("page.pageSize");
		if (currentPage != null) {
			page.setPageSize(Long.valueOf(pageSize));
		}
	}

}
